package com.feifan.monthhelper.wedget.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.View;

public class CirclePieView extends View {

    private Paint paint;
    //文字颜色
    private int textColor;
    //圆饼背景色
    private int bgColor;
    //圆饼扇形区域色
    private int arcColor;
    //圆饼扇形区域百分比
    private int arcPercent = 0;
    private RectF rectF;

    public CirclePieView(Context context) {
        this(context, null);
    }

    public CirclePieView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CirclePieView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public CirclePieView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    public void setArcPercent(int arcPercent) {
        this.arcPercent = arcPercent;
        postInvalidate();
    }

    private void init() {
        paint = new Paint();
        paint.setStyle(Paint.Style.FILL_AND_STROKE);

        textColor = Color.parseColor("#FFFFFF");
        arcColor = Color.parseColor("#FF66BA");
        bgColor = Color.parseColor("#FD8CCA");

        rectF = new RectF();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int cx = getWidth()/2;
        int cy = getHeight()/2;
        int radius = Math.min(getHeight(), getWidth())/2;
        paint.setColor(bgColor);
        canvas.drawCircle(cx, cy, radius, paint);

        paint.setColor(arcColor);
        rectF.set(0f, 0f, (float) getWidth(), (float) getHeight());
        canvas.drawArc(rectF, 0 - 90, arcPercent * 360 / 100, true, paint);

        paint.setColor(textColor);
        paint.setTextAlign(Paint.Align.CENTER);
        paint.setTextSize(dipToPx(getContext(), 13));
        Paint.FontMetrics metrics = paint.getFontMetrics();
        float mTextBaseLine = getHeight() / 2f - metrics.descent + (metrics.bottom - metrics.top) / 2;
        canvas.drawText(arcPercent + "%", cx, mTextBaseLine, paint);
    }

    /**
     * dp转px
     *
     * @param context context
     * @param dpValue dp
     * @return px
     */
    private static int dipToPx(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
